import React, { ReactElement, useState, useReducer, Dispatch, useEffect } from 'react'
import { Space, Button, Radio, Table, TablePaginationConfig } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import style from './index.module.less'
import { initialState, reducer } from './reducer'
import { getColumn } from './util'
import { DepartmentSchema } from '@src/components/schema/departmentSchema'
import { awaitWrap } from '@src/assets/js/tool'
import { getPersonListRequest } from './ajax'
import { AccountSchema } from '@src/components/schema/account'
import DetailModal from './components/detailModal'
import { TreeData } from '@src/components/schema/tree'
import RoleDetail from './components/roleDetail'
import DefaultRoleDetail from './components/defaultRoleDetail'
import { tenantCode } from '@src/assets/js/config'

interface Props {
  department: DepartmentSchema | null
  treeData: TreeData[]
}

interface IdMap { [k: string]: DepartmentSchema }

// 获取人员列表
async function getPersonList (d: DepartmentSchema, status: number, state: typeof initialState, dispatch: Dispatch<{type: string, data: any}>, setDataSource: (v: AccountSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  const structureid = tenantCode === d.key ? null : d.id
  const page = state.current === undefined ? 1 : state.current
  const limit = state.pageSize === undefined ? 10 : state.pageSize
  setLoading(true)
  const [e, data] = await awaitWrap(getPersonListRequest(d.tenant_code, structureid, status, page, limit))
  setLoading(false)
  if (e === null && data !== null) {
    dispatch({ type: 'total', data: data.total })
    setDataSource(data.list instanceof Array ? data.list.filter(li => li.id !== null) : [])
  }
}

// 改变表单
function tableChange (p: TablePaginationConfig, dispatch: Dispatch<any>): void {
  dispatch({ type: 'current', data: p.current })
  dispatch({ type: 'pageSize', data: p.pageSize })
}

// 初始化部门id映射
function initDepartmentMap (goal: IdMap, department: DepartmentSchema): void {
  goal[department.id] = department
  department.children.forEach(d => {
    initDepartmentMap(goal, d)
  })
}

function Main ({ department, treeData }: Props): ReactElement {
  const [loading, setLoading] = useState(false)
  const [state, dispatch] = useReducer(reducer, initialState)
  const [status, setStatus] = useState(1)
  const [dataSource, setDataSource] = useState<AccountSchema[]>([])
  const [departmentMap, setDepartmentMap] = useState<IdMap>({})
  const [visible, setVisible] = useState(false)
  const [roleVisible, setRoleVisible] = useState(false)
  const [modifyData, setModifyData] = useState<AccountSchema | null>(null)
  const [defaultVisible, setDefaultVisible] = useState(false)
  const refreshData = function (): void {
    if (department !== null && department !== undefined) {
      getPersonList(department, status, state, dispatch, setDataSource, setLoading).catch(e => console.error(e))
    }
  }
  useEffect(() => {
    refreshData()
  }, [department, status, state.current, state.pageSize])
  useEffect(() => {
    const o = {}
    if (department !== null && department !== undefined) {
      initDepartmentMap(o, department)
    }
    setDepartmentMap(o)
  }, [department])
  return (
    <div className={style.container}>
      <DetailModal visible={visible} department={department} refreshData={refreshData} data={modifyData} treeData={treeData} hide={() => { setVisible(false); setModifyData(null) }} />
      <RoleDetail visible={roleVisible} data={modifyData} hide={() => { setRoleVisible(false); setModifyData(null) }} />
      <DefaultRoleDetail visible={defaultVisible} data={modifyData} hide={() => { setDefaultVisible(false); setModifyData(null) }} />
      <div className={style['title-line']}>
        <span className={style.title}>{department !== null && department !== undefined ? department.name : ''}</span>
        <span className={style.subtitle}> {dataSource.length} (人）</span>
      </div>
      <div className={style['operate-line']}>
        <Space>
          <Button type='primary' icon={<PlusOutlined />} onClick={() => { setVisible(true) }}>添加员工</Button>
          {/* <Button>修改部门</Button> */}
        </Space>
        <Radio.Group value={status} onChange={e => setStatus(e.target.value)}>
          <Radio.Button value={1}>在职</Radio.Button>
          <Radio.Button value={0}>离职</Radio.Button>
        </Radio.Group>
      </div>
      <div>
        <Table loading={loading} columns={getColumn(departmentMap, setModifyData, setVisible, setRoleVisible, setDefaultVisible, refreshData)} dataSource={dataSource} rowKey='id' pagination={state} onChange={(pagination) => tableChange(pagination, dispatch)} size='small' />
      </div>
    </div>
  )
}

export default Main
